package xcore

import (
	"context"
	"fmt"
	"strings"
)

//var chars string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var chars string = "Ln8D5cTobg34yV9Gd6XaerSusBNmQUO0Iz1EHYJklvi7PpMjqw2AtRCxZfFKhW"

func Base10To62(ctx context.Context, v int64) (string, error) {
	return Base10ToX(ctx, v, 62)
}
func Base62To10(ctx context.Context, v string) (int64, error) {
	return BaseXTo10(ctx, v, 62)
}

/**
10进制数字按照进制转成字符串。
进制支持10~62，即数字10+26个字符大小写
*/
func Base10ToX(ctx context.Context, v int64, base int64) (string, error) {
	if err := validBase(base); err != nil {
		return "", err
	}
	var datas []byte
	for v > 0 {
		datas = append(datas, chars[v%base])
		v = v / base
	}
	reverse(datas)
	return string(datas), nil
}
func BaseXTo10(ctx context.Context, v string, base int64) (int64, error) {
	if err := validBase(base); err != nil {
		return 0, err
	}
	if len(v) <= 0 {
		return 0, fmt.Errorf("invalid value")
	}
	var num int64
	n := len(v)
	for i := 0; i < n; i++ {
		positionVal := strings.IndexByte(chars, v[i])
		num += pow(base, int64(n-i-1)) * int64(positionVal)
	}
	return num, nil
}
func validBase(base int64) error {
	if base < 10 || base > 62 {
		return fmt.Errorf("base must between 10 and 62")
	}
	return nil
}

func reverse(a []byte) {
	for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
		a[left], a[right] = a[right], a[left]
	}
}
func pow(v int64, n int64) int64 {
	var num int64 = 1
	for i := 0; int64(i) < n; i++ {
		num *= v
	}
	return num
}
